<template>
  <div class="search">
    <van-nav-bar title="商品搜索" left-arrow @click-left="$router.go(-1)" />

    <van-search show-action placeholder="请输入搜索关键词" clearable v-model="searchText">
      <template #action>
        <div @click="gosearch(searchText)">搜索</div>
      </template>
    </van-search>

    <!-- 搜索历史 -->
    <div class="search-history" v-if="historyList.length>0">
      <div class="title">
        <span>最近搜索</span>
        <van-icon name="delete-o" @click="clear" size="16" />
      </div>
      <div class="list">
        <div class="list-item"  v-for="item in historyList" :key="item" @click="gosearch(item)">{{ item }}</div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SearchIndex',
  data() {
    return {
      searchText: '',
      historyList: []
    };  
  },
  methods: {
    gosearch(key) {
      // 搜索逻辑
      console.log('搜索了：', key);
      const index=this.historyList.indexOf(key)
      if(index!==-1){
        this.historyList.splice(index,1)
        this.historyList.unshift(key) //unshift() 方法可向数组的开头添加一个或更多元素，并返回新的长度。
      }
      else{
        this.historyList.unshift(key)
        localStorage.setItem('searchHistory',JSON.stringify(this.historyList))
      }
      this.$router.push({ path: '/searchlist', query: { key } });
    },
    clear(){
      this.historyList=[]
      localStorage.removeItem('searchHistory')  
    } 
  },
  created() {
    const history=localStorage.getItem('searchHistory')
    if(history){
      this.historyList=JSON.parse(history) 
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  .searchBtn {
    background-color: #fa2209;
    color: #fff;
  }
  ::v-deep .van-search__action {
    background-color: #c21401;
    color: #fff;
    padding: 0 20px;
    border-radius: 0 5px 5px 0;
    margin-right: 10px;
  }
  ::v-deep .van-icon-arrow-left {
    color: #333;
  }
  .title {
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 15px;
  }
  .list {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    padding: 0 10px;
    gap: 5%;
  }
  .list-item {
    width: 15%;
    text-align: center;
    padding: 7px;
    line-height: 15px;
    border-radius: 50px;
    background: #fff;
    font-size: 13px;
    border: 1px solid #efefef;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-bottom: 10px;
  }
}
</style>